import { promises as fs, Dirent } from 'fs';
import config from './config';
import path = require('path');

const {
  inputDirPath,
  fileExtensions,
  ignoreDirsName,
  ignoreFilesName,
 } = config;


async function getFilesPath(dirPath = inputDirPath): Promise<readonly [string[], string[], string[]]> {
  const dir = await fs.opendir(dirPath);
  const files: string[] = [];
  const ignoreDirs: string[] = [];
  const ignoreFiles: string[] = [];

  for await (const dirent of dir) {
    const direntPath = path.join(dirPath, dirent.name);

    if (dirent.isDirectory()) {
      if (!isValidDir(dirent)) {
        ignoreDirs.push(direntPath);
        continue;
      }

      const [subFiles, subIgnoreDirs, subIgnoreFiles] = await getFilesPath(direntPath);
      files.push(...subFiles);
      ignoreDirs.push(...subIgnoreDirs);
      ignoreFiles.push(...subIgnoreFiles);
    } else {
      if (!isValidFile(dirent)) {
        ignoreFiles.push(direntPath);
        continue;
      }

      files.push(direntPath);
    }
  }

  return [files, ignoreDirs, ignoreFiles] as const;
}

function isValidDir(dirent: Dirent) {
  const { name } = dirent;
  let isValid: boolean;

  isValid = !ignoreDirsName.includes(name);
  return isValid;
}

function isValidFile(dirent: Dirent) {
  const { name } = dirent;
  let isValid: boolean;

  isValid = !ignoreFilesName.includes(name);
  if (isValid) {
    const fileExtension = path.extname(name);
    isValid = fileExtensions.includes(fileExtension);
  }

  return isValid;
}

export default getFilesPath;
